#!/usr/bin/env python3
# encoding=utf-8

from concurrent.futures import ThreadPoolExecutor, as_completed
import imaplib
from commom_api import get_sec_info, get_max_worker
from email_process import filter_info_init, is_mail_filter_info, parser_context_info, filter_folders_by_filelist
import logging
logger = logging.getLogger(__name__)


def get_mail_imap_handle(): 
    sinfo = get_sec_info()
    # 创建连接
    if sinfo['ssl'] == 1:
        conn = imaplib.IMAP4_SSL(sinfo['mail'], sinfo['port'])
    else:
        conn = imaplib.IMAP4(sinfo['mail'], sinfo['port'])
    # 登录服务器
    conn.login(sinfo['user'], sinfo['passwd'])# 注意输入的是邮箱授权码而不是真实QQ密码
    return conn

def get_imap_mail_info():
    emailinfo = []
    conn = get_mail_imap_handle()
    # 获取邮件列表
    status, msg30day = conn.select('INBOX', readonly=True) 
    while status != 'OK':
        logger.info(msg30day)
        status, msg30day = conn.select('INBOX', readonly=True) 

    msg30day = msg30day[0].decode('utf-8')
    # 搜索条件： UNSEEN ：未读    SEEN ：已读     ALL ：所有 
    # FROM "xxx" / SUBJECT "xxx"：按发件人或主题过滤。
    # 条件可通过逻辑运算符组合（如OR、AND），例如：
    criteria = 'ALL'
    # criteria = '(OR FROM "xxx@example.com")'
    rsearch, messages = conn.search(None, criteria)
    messages = messages[0].decode('utf-8').split(' ')
    # 检查搜索是否成功  
    if rsearch == 'OK':  
        logger.info("all %s found %d email" % (msg30day, len(messages)))  
        for msgid in reversed(messages):
            typ, data = conn.fetch(msgid, '(RFC822)')
            ret = is_mail_filter_info(data[0][1])
            if ret == 0:
                continue
            elif ret < 0:
                break
            oneinfo = parser_context_info(data[0][1])
            if len(oneinfo) == 0:
                continue
            for one in oneinfo:
                if one == None:
                    continue
                emailinfo.append(one)
    else:  
        logger.info("未找到符合条件的邮件") 

    # 退出服务器
    conn.logout()
    
    return emailinfo
'''
以下开始是通过 imapclient 实现
'''
from imapclient import IMAPClient, imap_utf7
def get_mail_imapclient_handle(): 
    sinfo = get_sec_info()
    # 创建连接
    conn = IMAPClient(host=sinfo['mail'], port=sinfo['port'], ssl=sinfo['ssl'])
    # 登录服务器
    conn.login(sinfo['user'], sinfo['passwd'])# 注意输入的是邮箱授权码而不是真实QQ密码
    return conn

def list_all_subfolders(client, allfolder, parent='', delimiter='/'):
    folders = client.list_folders(parent)
    for flags, delim, name in folders:
        if len(name.split('/')) == 2:
            if name not in allfolder:
                allfolder.append(name)
        full_path = f"{parent}{delim}{name}" if parent else name
        decoded_path = imap_utf7.decode(full_path.encode())
        
        if b'\\HasChildren' in flags:
            # 递归遍历子文件夹
            list_all_subfolders(client, allfolder, full_path, delim)
        # else:
        #     print(f"可操作的文件夹: {name}:{decoded_path}")
def get_emailinfo_from_folder(response):
    emailinfo = []
    for msg_id, data in response.items():
        ret = is_mail_filter_info(data[b'RFC822'])
        if ret <= 0:
            continue
        oneinfo = parser_context_info(data[b'RFC822'])
        if len(oneinfo) == 0:
            continue
        for one in oneinfo:
            if one == None:
                continue
            if one in emailinfo:
                continue
            emailinfo.append(one)
    return emailinfo

def get_data_by_imapclient(): 
    conn = get_mail_imapclient_handle()
    folders = []
    list_all_subfolders(conn, folders)
    folders = filter_folders_by_filelist(folders)
    folders.append('INBOX')
    
    taskparamlist = []
    for folder in folders:
        # messages = conn.search(["FROM data@tg.gtja.com"])
        # criteria = ["OR", "FROM", "data@tg.gtja.com", "FROM", "wbgz@htsc.com"]
        # criteria = ["SINCE", "20-Feb-2024"]
        conn.select_folder(folder, readonly=True)  # readonly避免标记邮件为已读
        messages = conn.search('ALL')
        logger.info(f"{folder} 找到 {len(messages)} 封邮件")
        response = conn.fetch(messages, ["RFC822"])#, "ENVELOPE"])
        taskparamlist.append(response)      
    with ThreadPoolExecutor(max_workers=get_max_worker()) as executor:
        futures = [executor.submit(get_emailinfo_from_folder, i) for i in taskparamlist]
        emailinfo = []
        # 按完成顺序处理任务
        for future in as_completed(futures):
            emailinfo += (future.result())
            # print(f"Result: {future.result()}")
    return emailinfo
    

def get_data_by_imap(): 
    filter_info_init()
    # emailinfo = get_imap_mail_info()
    emailinfo = get_data_by_imapclient()
    return emailinfo

if __name__=="__main__":
    get_data_by_imap()